package cn.swjtuhc.ss.hljapi.controller;

import cn.swjtuhc.ss.hljapi.common.Result;
import cn.swjtuhc.ss.hljapi.mapper.EssayMapper;
import cn.swjtuhc.ss.hljapi.pojo.Activity;
import cn.swjtuhc.ss.hljapi.pojo.Essay;
import cn.swjtuhc.ss.hljapi.pojo.Viewer;
import cn.swjtuhc.ss.hljapi.service.EssayService;
import cn.swjtuhc.ss.hljapi.service.ViewerService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author: chenximeng
 * @date: 2024/8/27 15:50
 */
@Slf4j
@RequestMapping("/api/essay")
@RestController
public class FrontEssayController {

    @Autowired
    private EssayService essayService;

    @Autowired
    private EssayMapper essayMapper;
    @Autowired
    private ViewerService viewerService;
    @GetMapping("/detail/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        return Result.success(essayService.findById(id));
    }
    @GetMapping("/list")
    public Result newsList() {
        LambdaQueryWrapper<Essay> wrapper = new LambdaQueryWrapper<Essay>()
                .last("limit 10");
        return Result.success(essayService.list(wrapper));
    }
    @GetMapping("/list/choose/{type}")
    public Result findByType(@PathVariable Integer type) {
        LambdaQueryWrapper<Essay> wrapper = new LambdaQueryWrapper<Essay>()
                .eq(Essay::getType, type)
                .last("limit 10");
        return Result.success(essayService.list(wrapper));
    }
    @GetMapping("/HomeNewList")
    public Result find() {
        LambdaQueryWrapper<Essay> wrapper = new LambdaQueryWrapper<Essay>()
                .last("limit 10");
        return Result.success(essayService.list(wrapper));
    }


    @GetMapping("/find")
    public Result findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                           // 默认的页码是1
                           @RequestParam(defaultValue = "10") Integer pageSize, // 默认的每页显示数量是10
                           @RequestParam(required = false) String search) {
        // 创建一个 Page<Essay> 对象
        Page<Essay> page = new Page<>(pageNum, pageSize);

        // 创建一个 LambdaQueryWrapper 对象，用于构建查询条件(支持很多种条件查询 )
        LambdaQueryWrapper<Essay> wrapper = Wrappers.<Essay>lambdaQuery();

        // 如果搜索字符串不为空，则添加模糊匹配条件
        if (!"".equals(search)) {
            wrapper.like(Essay::getTitle, search); // 使用 lambda 表达式来设置模糊匹配条件
        }

        // 使用正确的泛型调用 selectPage 方法
        Page<Essay> userPage = essayMapper.selectPage(page, wrapper);

        // 返回查询结果
        return Result.success(userPage);
    }
}
